package org.xs.web.http.servlet;

import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class ServletRequestSessionMap implements Map<String, Object>{

	private HttpServletRequest request;
	
	public ServletRequestSessionMap(HttpServletRequest request){
		this.request = request;
	}
	
	private HttpSession getSession(){
		return request.getSession(false);
	}
	
	@Override
	public void clear() {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean containsKey(Object key) {
		HttpSession  session= getSession();
		return session == null ? false : session.getAttribute((String)key) != null;
	}

	@Override
	public boolean containsValue(Object value) {
		throw new UnsupportedOperationException();
	}

	@Override
	public Set<java.util.Map.Entry<String, Object>> entrySet() {
		throw new UnsupportedOperationException();
	}

	@Override
	public Object get(Object key) {
		HttpSession session = getSession();
		return session == null? null : session.getAttribute((String)key);
	}

	@Override
	public boolean isEmpty() {
		throw new UnsupportedOperationException();
	}

	@Override
	public Set<String> keySet() {
		HttpSession session = getSession();
		if(session == null){
			return Collections.EMPTY_SET;
		}
		HashSet<String> keys = new HashSet<String>();
		Enumeration<String> elements = session.getAttributeNames();
		while(elements.hasMoreElements()){
			keys.add(elements.nextElement());
		}
		return keys;
	}

	@Override
	public Object put(String key, Object value) {
		HttpSession session = getSession();
		if(session == null){
			session = request.getSession(true);
		}
		Object result = session.getAttribute((String)key);
		session.setAttribute(key, value);
		return result;
	}

	@Override
	public void putAll(Map<? extends String, ? extends Object> m) {
		throw new UnsupportedOperationException();
	}

	@Override
	public Object remove(Object key) {
		HttpSession session = getSession();
		if(session == null){
			return null;
		}
		Object result = session.getAttribute((String)key);
		session.removeAttribute((String)key);
		return result;
	}

	@Override
	public int size() {
		throw new UnsupportedOperationException();
	}

	@Override
	public Collection<Object> values() {
		throw new UnsupportedOperationException();
	}

}
